(function() {
	let entry,
		// 配置所有应用的入口文件，程序将会按照data-main属性中设置的值进行索引查找
		// 如果你在引入此脚本的script标签上没有设置data-main属性，程序将会默认访问home.js文件
		app = {
			menu: 'menu'
		};

	(function() {
		let dataMain, scripts = document.getElementsByTagName('script'),
			eachScripts = function(el) {
				dataMain = el.getAttribute('data-main');
				if (dataMain) {
					entry = dataMain;
				}
			};

		[].slice.call(scripts).forEach(eachScripts);
	})();

	layui.config({
		//base: '/api-test/static/plugins/layui/lay/modules/',
		base: '/api-test/static/js/'
	}).extend(app).use(entry || 'menu');

})();

layui.use(['jquery', 'layer', 'form'], function() {
	let $ = layui.$;
	let layer = layui.layer;
	let form = layui.form;

	let account = sessionStorage.getItem('account');
	if (account == undefined || account.trim().length == 0) {
		window.location.href = "/api-test/page/login.html";
		return;
	}

	$('#index-name').text(sessionStorage.getItem('name')); //用户名


	//修改密码
	let indexPasswordDialog;
	$('#index-password').click(function() {
		indexPasswordDialog = layer.open({
			type: 1,
			title: '修改密码',
			area: ['400px', '240px'],
			skin: 'layer-ext-skin',
			content: $('#index-password-dialog'),
			btn: ['提交', '关闭'],
			yes: function(index, layero) {
				$('#index-password-form-submit').click(); //模拟点击 校验不能为空
			}
		});
	});

	//监听form表单提交
	form.on('submit(index-password-form-submit)', function(data) {
		let password = $('#index-password-form [name="password"]').val();
		let confirmPass = $('#index-password-form [name="confirmPass"]').val();
		if (base.isEmpty(password)) {
			layer.alert('密码不能为空!')
			return false;
		}
		if (password.length < 6) {
			layer.alert('密码长度不能小于6位!');
			return false;
		}
		if (password != confirmPass) {
			layer.alert('两次输入的密码不一致!');
			return false;
		}
		base.ajax({
			url: '/userUpdatePassword',
			data: {
				userId: sessionStorage.getItem('userId'),
				password: password.trim(),
				token: base.getToken()
			},
			success: function(res) {
				if (res.code == 0) {
					layer.alert('密码修改成功!', function(index) {
						layer.close(index);
						logout();
					});
				} else {
					layer.alert(res.msg);
				}
			}
		});
		return false;
	});

	//退出登录
	$("#logout").click(function() {
		layer.confirm('是否确认退出登录?', {
			btn: ['确定', '取消'] //按钮
		}, function(index) {
			layer.close(index);
			logout();
		}, function() {});
	});
	
	function logout(){
		base.ajax({
			url: '/logout',
			data: {
				token: base.getToken()
			},
			success: function(res) {
				if (res.code == 0) {
					sessionStorage.clear();
					window.location.href = "/api-test/page/login.html";
				} else {
					layer.alert(res.msg);
				}
			}
		});
	}

	//刷新
	$("#refresh").click(function() {
		let index = $("#appTabs").find(".layui-this").index();
		$("#appTabPage").find("iframe")[index].contentWindow.location.reload(true);
	});

});
